﻿#ifndef SERIAL_H
#define SERIAL_H

#include <QObject>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QDebug>
#include <QMessageBox>
#include <QTimer>

#include <QModbusClient>
#include <QModbusReply>

#include "define.h"

typedef struct
{
    QString port;
    quint32 baud;
    quint8 dataBit;
    quint8 stopBit;
    quint8 Parity;
} ModbusRtuParam_t;

class Modbus : public QObject
{
    Q_OBJECT
public:
    explicit Modbus(QObject *parent = nullptr);
    ~Modbus();

    void setMaddr(const quint8 &maddr);

signals:
    void refrAvailablePorts(QStringList portList);
    void dataReady(ModbusRegCmd_e, QModbusDataUnit);
    void modbusWriteFeedback(ModbusRegCmd_e, bool);
    void isUnenable(void);
    void disconnect(void);

public slots:
    void searchAvailablePorts(void); // 查询可用串口
    void setModbusParam(ModbusRtuParam_t info); // 设置串口
    void setModbusEnable(bool en, QString port, QString baud); // 设置串口使能状态
    void refrInfo(void);

    void modbusGetRegs(ModbusRegCmd_e type);
    void modbusGetRegs(ModbusRegCmd_e type, int regAddr, quint16 regNum);
    void modbusSetRegs(ModbusRegCmd_e type, QModbusDataUnit writeData);

    void onReadReady(QModbusReply *reply, ModbusRegCmd_e type);

private:
    quint8 m_maddr = 0x01;
    QModbusClient *m_modbusDevice = nullptr;

    QTimer *m_realTimeRefrsh = nullptr;
};

#endif // SERIAL_H
